package org.my.stock.util;

import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgnitionEx;

import java.sql.SQLException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyDongFangStock {

    public static String getUrl(String symbol) {
        StringBuilder sb = new StringBuilder();
        sb.append("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=");
        if (symbol.startsWith("3") || symbol.startsWith("00") || symbol.startsWith("4") || symbol.startsWith("8")) {
            sb.append("0." + symbol + "&_=1744518781845");
        } else if (symbol.startsWith("2") || symbol.startsWith("9")) {
            return null;
        }
        else {
            sb.append("1." + symbol + "&_=1744528942680");
        }
        //return String.format("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=0.%s&_=1744518781845", symbol);
        return sb.toString();
    }

    public static void updateAll() throws IgniteCheckedException {
        String springCfgPath = "/Users/chenfei/Documents/Java/my_database/my-stock/src/main/resources/default-config.xml";
        Ignite ignite = IgnitionEx.start(springCfgPath);
        CacheConfiguration<?, ?> cacheCfg = new CacheConfiguration<>("public_meta");
        cacheCfg.setSqlSchema("PUBLIC");

        IgniteCache<?, ?> cache = ignite.getOrCreateCache(cacheCfg);

        String sql = "SELECT symbol FROM public.type_stock GROUP BY symbol";
        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);
        fieldsQuery.setLazy(true);
        Iterator<List<?>> iterator = cache.query(fieldsQuery).iterator();
        while (iterator.hasNext()) {
            List<?> it = iterator.next();
            if (!it.isEmpty()) {
                getData(cache, it.get(0).toString());
            }
        }
    }

    public static void getData(IgniteCache<?, ?> cache, String symbol) {
        String url = getUrl(symbol);
        if (url != null) {
            HttpClient httpClient = BrotliHttpClientHelper.createBrotliClient();

            try {
                // 1. 创建 GET 请求
                HttpGet request = new HttpGet(url);

                // 2. 设置请求头（防止被服务器拒绝）
                request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
                request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                request.setHeader("Accept-Encoding", "gzip, deflate, br");
                request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
                request.setHeader("Cache-Control", "max-age=0");
                request.setHeader("Connection", "keep-alive");
                request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; fullscreengg=1; fullscreengg2=1; st_si=66098437338071; emshistory=%5B%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%2C%22undefined%22%5D; HAList=ty-0-000893-%u4E9A%u94BE%u56FD%u9645%2Cty-90-BK0712-%u4E00%u5E26%u4E00%u8DEF%2Cty-1-600171-%u4E0A%u6D77%u8D1D%u5CAD%2Cty-90-BK0854-%u534E%u4E3A%u6982%u5FF5%2Cty-1-601398-%u5DE5%u5546%u94F6%u884C%2Cty-90-BK0968-%u56FA%u6001%u7535%u6C60%2Cty-0-300661-%u5723%u90A6%u80A1%u4EFD%2Cty-90-BK0638-%u521B%u4E1A%u6210%u4EFD%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-0-300782-%u5353%u80DC%u5FAE; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=96; st_psi=2025041315314915-113300300815-4079987765; st_asi=delete");
                request.setHeader("Host", "push2his.eastmoney.com");
                request.setHeader("Sec-Fetch-Dest", "document");
                request.setHeader("Sec-Fetch-Mode", "navigate");
                request.setHeader("Upgrade-Insecure-Requests", "1");

                // 3. 执行请求并获取响应
                HttpResponse response = httpClient.execute(request);

                // 4. 检查状态码
                //int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("所属类型: " + symbol);

                // 5. 读取响应内容
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 关键：使用 UTF-8 编码转换解压后的字节流
                    String content = EntityUtils.toString(entity, "UTF-8");
                    //toDb(ignite, cache, content, type_name, day);
                    toDb(cache, content, symbol);
                    System.out.println("解码内容:\n" + content);
                }

            } catch (Exception e) {
                System.err.println("请求失败: " + e.getMessage());
            } finally {
                // 6. 释放连接（重要！）
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

    public static void toDb(IgniteCache<?, ?> cache, final String line, String symbol) throws SQLException {
        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(line);

        if (matcher.find()) {
            String result = matcher.group(1); // 获取第一个捕获组内容

            LinkedTreeMap m = MyUtil.getGson().fromJson(result, new TypeToken<LinkedTreeMap>() {}.getType());
            LinkedTreeMap data = (LinkedTreeMap) m.get("data");
            List klines = (List) data.get("klines");
            String name = (String) data.get("name");

            for (int i = klines.size() - 1; i >=  klines.size() - 20; i--) {
                System.out.println(klines.get(i).toString());
                String dl = klines.get(i).toString();
                String[] vs = dl.split(",");
                //List mt = MyUtil.getGson().fromJson(klines.get(i).toString(), new TypeToken<List>() {}.getType());
                if (hasUpdate(cache, symbol, vs[0]) == false) {
                    //String sql = "insert into public.df_stock_date (symbol, price, main_fund, main_fund_bf, name, zhangdie, stock_date) values ('" + symbol + "', " + vs[11] + ", " + vs[1] + ", " + vs[6] + ", '" + name + "', " + vs[12] + ", '" + vs[0] + "')";
                    //cache.query(new SqlFieldsQuery(sql)).getAll();
                    updateDate(cache, symbol, vs[11], vs[1], vs[6], name, vs[12], vs[0]);
                } else {
                    break;
                }
            }
        }
    }

    /**
     * PK id
     * */
    public static Long getPkId(IgniteCache<?, ?> cache) {
        String sql = "select count(id) from public.df_stock_date";
        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);
        List<List<?>> lst = cache.query(fieldsQuery).getAll();
        if (lst.isEmpty())
            return 0L;
        List<?> rs = lst.get(0);
        return (Long)rs.get(0);
    }

    /**
     * 判断 symbol 的数量是否是 20，如果不是 20，就修改最后一项的数据
     * */
    public static void updateDate(IgniteCache<?, ?> cache, String symbol, String price, String main_fund, String main_fund_bf, String name, String zhangdie, String stock_date) {
        Long symbolCount = getSymbolCount(cache, symbol);
        if (symbolCount <= 20) {
            if (symbolCount < 20) {
                Long id = getPkId(cache) + 1;
                String sql = "insert into public.df_stock_date (id, symbol, price, main_fund, main_fund_bf, name, zhangdie, stock_date) values (" + id + ", '" + symbol + "', " + price + ", " + main_fund + ", " + main_fund_bf + ", '" + name + "', " + zhangdie + ", '" + stock_date + "')";
                cache.query(new SqlFieldsQuery(sql)).getAll();
            } else {
                // 修改最后一项的数据
                Long pkid = getSymbolLastId(cache, symbol);
                String sql = "update public.df_stock_date SET set price = "+ price +", main_fund = "+ main_fund +", main_fund_bf = "+ main_fund_bf +", zhangdie = "+ zhangdie +", stock_date = '"+ stock_date +"' WHERE id = " + pkid.toString();
                cache.query(new SqlFieldsQuery(sql)).getAll();
            }
        }
    }

    /**
     * 获取 Symbol 的个数
     * */
    public static Long getSymbolLastId(IgniteCache<?, ?> cache, String symbol) {
        String sql = "select id from public.df_stock_date where symbol = '"+ symbol +"' ORDER BY stock_date asc LIMIT 0, 1";
        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);
        List<List<?>> lst = cache.query(fieldsQuery).getAll();
        if (lst.isEmpty())
            return 0L;
        List<?> rs = lst.get(0);
        return (Long)rs.get(0);
    }

    /**
     * 获取 Symbol 的个数
     * */
    public static Long getSymbolCount(IgniteCache<?, ?> cache, String symbol) {
        String sql = "select count(id) from public.df_stock_date where symbol = '"+ symbol +"'";
        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);
        List<List<?>> lst = cache.query(fieldsQuery).getAll();
        if (lst.isEmpty())
            return 0L;
        List<?> rs = lst.get(0);
        return (Long)rs.get(0);
    }

    public static boolean hasUpdate(IgniteCache<?, ?> cache, String symbol, String stock_date) {
//        String sql = "select symbol from public.df_stock_date where symbol = '"+ symbol +"' and stock_date = '"+ stock_date +"'";
//        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);

        String sql = "select symbol from public.df_stock_date where symbol = ? and stock_date = ?";
        SqlFieldsQuery fieldsQuery = new SqlFieldsQuery(sql);
        fieldsQuery.setArgs(symbol, stock_date);
        List lst = cache.query(fieldsQuery).getAll();
        if (lst.isEmpty())
            return false;
        return true;
    }

    public static int getInt() {
        Date date = new Date(); // 当前时间

        // 将时间戳（long）强制转换为 int（需谨慎，可能溢出）
        int timestamp = (int) date.getTime();

        System.out.println("时间戳（int）: " + timestamp);
        return timestamp;
    }
}
